<template>
  <div>
    <el-form :model="fromData" :rules="rules" ref="ruleForm" label-width="100px">
      <el-form-item label="车场名称:" prop="parkName">
        <el-input v-model="fromData.parkName" size="mini"></el-input>
      </el-form-item>

      <el-form-item label="联系电话:" prop="telephone">
        <el-input v-model="fromData.telephone" size="mini"></el-input>
      </el-form-item>

      <el-form-item label="总车位数:" prop="totalParkSpace">
        <el-input v-model.number="fromData.totalParkSpace" size="mini"></el-input>
      </el-form-item>
      
      <el-form-item label="剩余车位数:" prop="emptyParkSpace">
        <el-input type="" v-model.number="fromData.emptyParkSpace" maxlength="5" size="mini"></el-input>
      </el-form-item>

      <el-form-item label="预约车位:" prop="reserveParkSpace">
        <el-input v-model.number="fromData.reserveParkSpace" size="mini"></el-input>
      </el-form-item>

      <el-form-item label="车场纬度:" prop="latitude">
        <el-input v-model.number="fromData.latitude" size="mini"></el-input>
      </el-form-item>

      <el-form-item label="车场经度:" prop="longitude">
        <el-input v-model.number="fromData.longitude" size="mini"></el-input>
      </el-form-item>

      <el-form-item label="车场地址:" prop="parkAddress">
        <el-input v-model="fromData.parkAddress" style="width: 500px;" size="mini"></el-input>
      </el-form-item>

      <el-form-item label="是否支持无感" style="display: block;">
        <el-radio v-model="fromData.isAutopay" label="1">支持</el-radio>
        <el-radio v-model="fromData.isAutopay" label="0">不支持</el-radio>
      </el-form-item>

      <el-form-item label="车场图片:">
        <ul class="imgshow">
          <li v-for="(item,index) in fromData.parkImgUrls">
            <img style="height: 100px;" :src="item">
            <div v-if="item" class="icon-delete">
              <i class="el-icon-delete" @click.stop="rmImage(index)" />
            </div>
          </li>
        </ul>
        <ul class="uploadbtn">
          <li @click="uploadBtn" id="image-uploader">
            <input type="file" @change="upload" multiple ref="file" style="display: none;" />
            <i class="el-icon-upload" />
          </li>
        </ul>
      </el-form-item>
    </el-form>

    <el-dialog title="图片剪裁" :visible.sync="dialogVisible" append-to-body>
        <div class="cropper-content">
            <div class="cropper" style="text-align:center">
                <vueCropper
                    ref="cropper"
                    :img="option.img"
                    :outputSize="option.outputSize"
                    :outputType="option.outputType"
                    :info="option.info"
                    :canScale="option.canScale"
                    :autoCrop="option.autoCrop"
                    :autoCropWidth="option.autoCropWidth"
                    :autoCropHeight="option.autoCropHeight"
                    :fixed="option.fixed"
                    :fixedBox="option.fixedBox"
                    :fixedNumber="option.fixedNumber"
                ></vueCropper>
            </div>
        </div>
       <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="finish" :loading="loading">确认</el-button>
       </div>
    </el-dialog>

    <div style="text-align: center;">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="confirm('ruleForm')" :loading="loading">确认</el-button>
    </div>


  </div>
</template>

<script>
  import { VueCropper } from 'vue-cropper'
export default {
  components: { VueCropper },
  props: ['row'],
  data() {
    var validatorPhone = function (rule, value, callback) {
      if (value == undefined) {
        callback(new Error('手机号不能为空'))
      } else if (!/^1\d{10}$/.test(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    return {
      picsList: [],  //页面显示的数组
      // 防止重复提交
      loading: false,
      fileinfo:{},
      cropperUrl: [],
      fromData: {},
      imageList: [],
      dialogVisible: false,
      // 裁剪组件的基础配置option
      option: {
          img: '', // 裁剪图片的地址
          info: true, // 裁剪框的大小信息
          outputSize: 1, // 裁剪生成图片的质量
          outputType: 'jpeg', // 裁剪生成图片的格式
          canScale: true, // 图片是否允许滚轮缩放
          autoCrop: true, // 是否默认生成截图框
          autoCropWidth: 400, // 默认生成截图框宽度
          autoCropHeight: 200, // 默认生成截图框高度
          fixedBox: false, // 固定截图框大小 不允许改变
          fixed: true, // 是否开启截图框宽高固定比例
          fixedNumber: [2, 1], // 截图框的宽高比例
          full: true, // 是否输出原图比例的截图
          canMoveBox: false, // 截图框能否拖动
          original: false, // 上传图片按照原始比例渲染
          centerBox: false, // 截图框是否被限制在图片里面
          infoTrue: true, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
          canMove:true,
      },
      rules: {
        parkName: [{ required: true, message: '车场名称不能为空', trigger: 'blur' }],
        telephone: [{ required: true, validator: validatorPhone, trigger: 'blur' }],
        totalParkSpace: [{ required: true, message: '总车位数不能为空', trigger: 'blur' }],
        emptyParkSpace: [{ required: true, message: '请输入剩余车位', trigger: 'blur' }],
        reserveParkSpace: [{ required: true, message: '预约车位数不能为空', trigger: 'blur' }],
        parkAddress: [
          { required: true, message: '车场地址不能为空', trigger: 'blur' },
          { min: 1, max: 75, message: '长度在1 到 75 个字符', trigger: 'blur' }
        ],
        latitude: [{ required: true, message: '车场纬度不能为空', trigger: 'blur' }],
        longitude: [{ required: true, message: '车场经度不能为空', trigger: 'blur' }],
      }


    }
  },
  computed: {},
  watch: {
    
  },
  mounted() {
   
  },
  created() {
    this.getParkImg();
  },
  methods: {
    getParkImg() {
      this.$axios({
        method: 'get',
        url: '/park/park-info/get-by-id',
        params: {id: this.row.id}
      }).then(res => {
        if(res.code == 200) {
          this.fromData = res.data;
          this.fromData.isAutopay = this.fromData.isAutopay == 1 ? '1' : '0'
        }
      })
    },
    confirm(formName) {
      this.$refs[formName].validate((valid) => {
        if(valid) {
          this.$axios({
            method: 'post',
            url: '/park/park-info/update',
            data: this.fromData
          }).then((res) => {
            if(res.code == 200) {
              this.$message.success('编辑成功！');
              this.$emit('closeDialog');
              this.$emit('refresh');
            } else {
              this.$message.warning(res.desc);
            }
          })
        }
      })
    },
    cancel() {
      this.$emit('closeDialog',false)
    },
    finish() {
      this.$refs.cropper.getCropBlob((data) => {
          var fileName = 'goods' + this.fileinfo.uid
          let formData = new FormData()
          formData.append('files', data, this.fileinfo)
          var image = { url: null, percent: 0 }
          this.imageList.push(image)
          this.uploadAxios(formData, image)
      })

      this.dialogVisible = false;
      // this.loading = false;
    },
    uploadBtn(){
      this.$refs.file.dispatchEvent(new MouseEvent('click'))
    },
    upload(e) {
      let files = e.target.files
      this.$nextTick(() => {
          this.option.img = URL.createObjectURL(files[0]);
          this.fileinfo = files[0].name;
      })
      for (let i = 0; i < files.length; i++) {
        const isImg = files[i].type.indexOf('image') > -1
        const isLimit = files[i].size / 1024 / 1024 < 10

        if (!isImg) {
          this.$message.error('请上传图片格式!')
          return false
        }
        if (!isLimit) {
          this.$message.error('大小不能超过 10MB!')
          return false
        }
        let formData = new FormData()
        formData.append('files', files[i])

        var image = { url: null, percent: 0 }
        this.imageList.push(image)

        this.uploadAxios(formData, image)
      }
    },
    uploadAxios(formData, image){
      this.$axios({
        url: 'https://file.zmzncs.com/upload/upload-batch',
        method: 'post',
        data: formData,
        timeout: 1000 * 60, // 请求超时时间
        onUploadProgress: (progress)=> {
          image.percent = Math.round(progress.loaded / progress.total * 100)
        }
      }).then((res) => {
        if (res.code == 200) {
          image.percent = 100
          image.url = res.data[0].url
          this.fromData.parkImgUrls.push(image.url)
          //  组件返回值
          // var urlList = []
          // this.imgs = [];
          // this.imageList.forEach((image)=> {
          //   this.imgs.push(image.url)
          // })
          // var urls = urlList.toString()
          // this.$emit('input', urls)
        }
      }).catch(err => {})
    },
    rmImage(index) {
      this.$refs.file.value = ''
      this.fromData.parkImgUrls.splice(index, 1)
      this.imgs.splice(index,1)

      var urlList = []
      this.fromData.parkImgUrls.forEach((image)=> {
        urlList.push(image.url[1])
      })
      var urls = urlList.toString()
      this.$emit('input', urls)
    },
    imgLoad(e, index) {
      var scaleW = 200/e.path[0].offsetWidth
      var scaleH = 200/e.path[0].offsetHeight

      var scale = scaleW <= scaleH ? scaleW : scaleH

      e.path[0].style.transform = 'scale(' + scale + ')'
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-form-item {
    display: inline-block;
  }

  .el-input {
    width: 200px;
  }


  #image-uploader {
    &:hover {
      border: 1px dotted #1989fa;
      .el-icon-upload {
        color: #46a6ff;
      }
    }
    .el-icon-upload {
      font-size: 48px;
      margin: 50px;
    }
  }
  .cropper-content{
      width:500px;height:500px;background: pink;
  }
  .cropper{
      width:500px;
      height:500px;
      background: yellow;
  }
  .uploadbtn {
    display: flex;
    flex-wrap: wrap;
    li {
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      margin: 5px;
      border: 1px dotted #8c939d;
      cursor: pointer;
      border-radius: 10px;
      width: 100px;
      height: 100px;
      .icon-delete {
        display: flex;
        align-items: center;
        justify-content: center;
        position: absolute;
        width: 100%;
        height: 100%;
        cursor: default;
        &:hover {
          background-color: rgba(0, 0, 0, .5);
          .el-icon-delete {
            opacity: 1;
          }
        }
        .el-icon-delete {
          font-size: 48px;
          margin: 50px;
          opacity: 0;
          cursor: pointer;
          color: #FFFFFF;
          &:hover {
            color: #46a6ff;
          }
        }
      }
    }
  }
  .imgshow {
    list-style: none;
    display: flex;
    flex-wrap: wrap;
  }
  .imgshow li {
    margin-right: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    .icon-delete {
      display: flex;
      align-items: center;
      justify-content: center;
      position: absolute;
      width: 100%;
      height: 100%;
      cursor: default;
      &:hover {
        background-color: rgba(0, 0, 0, .5);
        .el-icon-delete {
          opacity: 1;
        }
      }
      .el-icon-delete {
        font-size: 48px;
        margin: 50px;
        opacity: 0;
        cursor: pointer;
        color: #FFFFFF;
        &:hover {
          color: #46a6ff;
        }
      }
    }
  }
</style>
